package com.isyscore.os.metadata.service.diop;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.google.common.base.Strings;
import com.isyscore.device.common.util.JsonMapper;
import com.isyscore.os.metadata.model.dto.diop.DiopRegisterReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RegisterService {

    @Autowired
    private DIOPConfiguration diopConfiguration;

    private ScheduledFuture<?> registerTimer;

    @PostConstruct
    public void register() {
        if (Strings.isNullOrEmpty(diopConfiguration.getRegisterUrl())) {
            return;
        }
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
        DiopRegisterReq registerDTO = new DiopRegisterReq();
        registerDTO.setServiceId(diopConfiguration.getServiceId());
        registerDTO.setImportUrl(diopConfiguration.getImportUrl());
        registerDTO.setExportUrl(diopConfiguration.getExportUrl());
        registerDTO.setDataTypesUrl(diopConfiguration.getDataTypesUrl());
        String body = JsonMapper.toAlwaysJson(registerDTO);
        this.registerTimer = executor.scheduleAtFixedRate(() -> {
            try {
                HttpRequest request = HttpRequest.post(diopConfiguration.getRegisterUrl())
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .timeout(10000)
                        .body(body);
                HttpResponse response = request.execute();
                if (response.isOk()) {
                    this.registerTimer.cancel(false);
                    executor.shutdown();
                }
            } catch (Exception e) {
                log.error("注册DIOP失败：" + diopConfiguration.getRegisterUrl(), e);
            }
        }, 10, 60, TimeUnit.SECONDS);
    }


}
